###############################################
# Dynamic DiD: Visas Haiti and Crime Concerns
###############################################

rm(list=ls())

library(Hmisc)
library(readstata13)
library(foreign)
library(tidyverse)
library(did)
library(ggplot2)
set.seed(1111)

#sink("21_nine_exposure.txt")

############################
# Read and prepare data 
############################

# load data
load("final_county_2023april6.RData")
names(d_county)

#######################
# Results 
#######################

# remove 10 survey
table(d_county$survey)
d_county = d_county[d_county$survey<10,]
table(d_county$survey)

# d-did
out3 <- att_gt(yname = "crime_concerns_s",
               gname = "first.treat_haiti",
               idname = "county",
               tname = "survey",
               data = d_county)

es3 <- aggte(out3, type = "dynamic",na.rm = TRUE)

# table formal to prepare plot
event_study_diff_never <-   data.frame(
  type          = "dynamic",
  term = paste0('ATT(', es3$egt, ")"),
  event.time= es3$egt,
  estimate  = es3$att.egt,
  std.error = es3$se.egt,
  conf.low  = es3$att.egt - es3$crit.val.egt * es3$se.egt,
  conf.high = es3$att.egt + es3$crit.val.egt  * es3$se.egt)

# plot
p_es_never2 <- ggplot(data = event_study_diff_never,
                     mapping = aes(x = event.time, y = estimate)) +
  geom_line(size = 0.5, alpha = 2, colour = "black") +
  theme_light()  +
  geom_vline(xintercept = 0-0.05, color = 'grey', size = 1.2, linetype = "dotted") + 
  geom_hline(yintercept = 0, colour="black",  linetype = "dotted")+
  geom_pointrange(aes(ymin = conf.low, ymax = conf.high), show.legend = FALSE, linetype= 1, size = 1.1,
                  color=ifelse(event_study_diff_never$event.time<0,"gray60","black"))+
  xlab("Event time") +
  ylab("Event Study Estimate") +
  scale_x_continuous(breaks = c(-7:8)) +
  scale_y_continuous(limits = c(-4,4)) +
  theme(axis.text.y = element_text(size = 14),axis.title.y = element_text(size = 18)) +
  theme(axis.text.x = element_text(size = 14),axis.title.x = element_text(size = 18)) +
  theme(axis.title = element_text(color="black",  size = 12))+
  theme(plot.title=ggtext::element_markdown(size = 12,
                                            color="black",
                                            hjust=0,
                                            lineheight=1.2)
  ) +
  annotate(geom="text", x=3.8, y=3.1, label="Average of post-treatment coefficients: 
                                            0.642* 
                                           (0.233)",
           color="black",
           size = 7)

# figure
tiff('figureA4.tiff', units="in", width=10, height=7, res=200, compression = 'lzw')
p_es_never2
dev.off()

sink()
